/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.evolve.webbot.portal;
import  java.util.Date;
import  java.text.SimpleDateFormat;
import  com.gargoylesoftware.htmlunit.BrowserVersion;
import  java.util.List;
import  java.util.Iterator;
import  java.net.URL;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.html.FrameWindow;
import  com.gargoylesoftware.htmlunit.html.HtmlElement;
import  com.gargoylesoftware.htmlunit.html.HtmlForm;
import  com.gargoylesoftware.htmlunit.html.HtmlSelect;
import  com.gargoylesoftware.htmlunit.html.HtmlPage;
import  com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import  com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import  com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import  com.gargoylesoftware.htmlunit.html.HtmlImage;

import  com.gargoylesoftware.htmlunit.html.HtmlInput;
import  com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import  com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import  com.gargoylesoftware.htmlunit.WebRequest;

import  java.io.IOException;
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileOutputStream;
import  java.io.InputStream;
import  java.io.OutputStream;
import  com.evolve.webbot.file.CommonDataFile;
import java.util.ArrayList;
import  javax.swing.*;
import  com.evolve.webbot.bean.LinkRetail;
import com.evolve.webbot.file.CommonErrorFile;
import  com.evolve.webbot.util.Utileria;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 *
 * @author DarthAE
 */
public class RetailLink
{
   public String path;
   public static String WB_MAIN_DIR="evolve-webbot";
   public static String RETAIL_MAIN_DIR="retail-webbot";
   public static String RETAIL_PROP_DIR="retail-properties";
   public static String RETAIL_PROP_ARC="retailPortal.properties";
   public static String RETAIL_FILE_DIR="retail-files";
   public static String RETAIL_FILE_NAME ="retail-vyc-";
   public static String RETAIL_ARC_EXT =".txt";   
   private final String URL_BASE ="https://retaillink.wal-mart.com";
   public static String RETAIL_ERROR_FILE="sears-error-";
   private final String FILE_EXT =".txt";
   
   static Logger log = Logger.getLogger( RetailLink.class );
   
   public JTextArea jtextArea;
   
   public String wFileName;
    
    public RetailLink(){}
    
    public RetailLink(String path)
    {
        this.path= path;
    }
    
    public RetailLink(String path,JTextArea jtextArea)
    {
        this.path= path;
        this.jtextArea=jtextArea;
    }   
    
    public void retailLinkAcces(int opt)
    {
       String fecha="";
       String dia="";
       String errorFilePath ="";
       Properties properties = new Properties();
       int indPortalEjec       = 0;
       
       Date thisDate = new Date();
       
       SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
       SimpleDateFormat shf = new SimpleDateFormat("HHmmss");
       
       this.jtextArea.append("\n[+]recuperando archivo retaillink"); 
       
       WebClient wc = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
       wc.setJavaScriptEnabled(true);
       wc.setThrowExceptionOnScriptError(false);
       wc.setAjaxController(new NicelyResynchronizingAjaxController());
       
       try{
            wc.setUseInsecureSSL(true);
          }catch(Exception e){System.out.println(e);}
              
       String value  = "";
       String idFile = "";

       Date fileDate = new Date();
       SimpleDateFormat sdf01 = new SimpleDateFormat("ddMMyyyy");
       SimpleDateFormat sdf02 = new SimpleDateFormat("yyyy");
       
       Utileria util = new Utileria();
       CommonErrorFile   cef = new CommonErrorFile();
       
       try{
             errorFilePath = this.path+File.separator+WB_MAIN_DIR+
                                File.separator+RETAIL_MAIN_DIR+
                                File.separator+RETAIL_FILE_DIR+
                                File.separator+RETAIL_ERROR_FILE+
                                sdf.format(thisDate)+"-"+
                                shf.format(thisDate)+".txt";
           
             FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                                 File.separator+RETAIL_MAIN_DIR+
                                                                 File.separator+RETAIL_PROP_DIR+
                                                                 File.separator+RETAIL_PROP_ARC);
             properties.load(fis);
                
          }catch(IOException ioe){log.error("[-]error al leer archivo de properties portal retail link ",ioe);}
       
       
       try{
            indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));
            
            
            if(indPortalEjec == 1)
            {
                HtmlPage          pg1 = (HtmlPage)wc.getPage("https://rllogin.wal-mart.com/rl_security/rl_logon.aspx?ServerType=IIS1&CTAuthMode=BASIC&language=en&CT_ORIG_URL=%2F&ct_orig_uri=%2F");
                HtmlForm          fr1 = (HtmlForm)pg1.getFormByName("frmLogin");
                HtmlTextInput     ti1 = (HtmlTextInput)fr1.getInputByName("txtUser");
                HtmlPasswordInput pw1 = (HtmlPasswordInput)fr1.getInputByName("txtPass");
                
                ti1.setValueAttribute(properties.getProperty("Portal.user"));
                pw1.setValueAttribute(properties.getProperty("Portal.passwd"));
                
                log.info(properties.getProperty("Portal.user")+" : "+properties.getProperty("Portal.passwd"));

                HtmlSubmitInput in1 =(HtmlSubmitInput)fr1.getInputByName("Login");

                HtmlPage  pg2  = (HtmlPage)in1.click();

                HtmlPage          pg3 = (HtmlPage)wc.getPage("https://retaillink.wal-mart.com/sitemap/sitemap.aspx");
            
                HtmlPage          pg4 = (HtmlPage)wc.getPage("https://retaillink.wal-mart.com/mydss/?ukey=W2441");
            
                List<HtmlAnchor> anchorList =pg4.getAnchors();
                HtmlAnchor an1=null;
                HtmlAnchor an2=null;
            
                for (Iterator iter = anchorList.iterator(); iter.hasNext();)
                {
                  an1=(HtmlAnchor)iter.next();

                  if(an1.getOnClickAttribute().compareTo("changeContent('Homepage_status.aspx?ApplicationId=300')")==0)
                  {
                      an2=an1;
                  }
                }
            
                HtmlPage pg5 = (HtmlPage)an2.click();
            
                List<HtmlAnchor> anchorList1 =pg5.getAnchors();
                HtmlAnchor an3=null;
                HtmlAnchor an4=null;            
            
                for (Iterator iter = anchorList1.iterator(); iter.hasNext();)
                {
                  an3=(HtmlAnchor)iter.next();
                }
            
                List<FrameWindow> windowList =pg5.getFrames();
                FrameWindow fwh = null;
            
                for (Iterator iter = windowList.iterator(); iter.hasNext();)
                {
                  FrameWindow fw=(FrameWindow)iter.next();

                  if(fw.getName().compareTo("JobTable")==0)
                  {
                      fwh=fw;
                  }
                }
            
                HtmlPage pg6=(HtmlPage)windowList.get(1).getEnclosedPage();         
            
            List<?> he1 =pg6.getByXPath("//span");
            
            HtmlElement el1 = null;
            HtmlElement el2 = null;
            int k=0;
            ArrayList<String> linkList = new ArrayList<String>();
            ArrayList<String> strDates = new ArrayList<String>();
            
            for (Iterator iter = he1.iterator(); iter.hasNext();)
            {
              el1=(HtmlElement)iter.next();              
              
              if(k==0)
              {
                 log.info("Nombre del Link: "+el1.getTextContent());
                 
                 HtmlPage pg07 = (HtmlPage)el1.click();
                 wc.waitForBackgroundJavaScriptStartingBefore(1000);
                 synchronized (pg07) {pg07.wait(1000);}
                 
                 value = pg07.asXml();
                 value = value.substring(value.indexOf("window.parent.JobTable.JodIdArray"));   
              }
              
              k++;
            }

            System.out.println(value);   
            
            linkList=util.getRetailFileLinks(value);     
            
            strDates = util.getRetailFileLinksDates(value);
            
            for(int i=0;i<linkList.size();i++)
            {
                log.info("link de descarga: "+linkList.get(i));
            }
            
            for(int i=0;i<strDates.size();i++)
            {
                log.info("fechas descarga: "+strDates.get(i));
            }            
            
/*----------------------------------------------------------------------------*/            
/*----------------------------------------------------------------------------*/
            ArrayList<String> listaFechas= new ArrayList<String>();
            ArrayList<String> linkListCopy = new ArrayList<String>();
            linkListCopy=util.getRetailFileLinks(value,0);
            
            System.out.println("[-] "+linkListCopy.size());
            
            if(0==linkListCopy.size())
            {
               linkListCopy.clear(); 
               linkListCopy.addAll(linkList);
            }
            
            for(int i=0;i<linkListCopy.size();i++)
            {
                /*System.out.println(linkList.get(i).substring(0,linkList.get(i).indexOf("|"))+" "+
                                   linkList.get(i).substring(linkList.get(i).indexOf("|")+1));*/
                try{
                fecha=linkListCopy.get(i).substring(0,linkListCopy.get(i).indexOf("|"));
                fecha = fecha.substring(11,18);
                dia="";
                
                }catch(Exception e){System.out.println(e);}

                
                if(fecha.trim().contains("Jan"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"01"+ dia;
                }
                else
                if(fecha.trim().contains("Feb"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"02"+ dia;
                }
                else
                if(fecha.trim().contains("Mar"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"03"+ dia;
                }
                else                 
                if(fecha.trim().contains("Apr"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"04"+ dia;
                }
                else  
                if(fecha.trim().contains("May"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"05"+ dia;
                }
                else                  
                if(fecha.trim().contains("Jun"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"06"+ dia;
                }
                else                 
                if(fecha.trim().contains("Jul"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"07"+ dia;
                }
                else                
                if(fecha.trim().contains("Aug"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"08"+ dia;
                }
                else
                if(fecha.trim().contains("Sep"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"09"+ dia;
                }
                else
                if(fecha.trim().contains("Oct"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                    fecha=sdf02.format(fileDate)+"10"+ dia;
                }
                else
                if(fecha.trim().contains("Nov"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                   fecha=sdf02.format(fileDate)+"11"+dia;
                }
                else
                if(fecha.trim().contains("Dec"))
                {
                    dia=(fecha.substring(fecha.length()-2,fecha.length())).trim();
                    if(dia.length()==1){dia="0"+dia;}
                   fecha=sdf02.format(fileDate)+"12"+dia;
                }                
                listaFechas.add(fecha);
                System.out.println(fecha.trim());
            }                
            
            for(int i=0;i < listaFechas.size();i++)
            {
                if(String.valueOf(i).length()==1)
                {idFile="0"+i;}
                else
                {idFile=String.valueOf(i);}
                
                InputStream  is  = wc.getPage(URL_BASE+linkList.get(i)).getWebResponse().getContentAsStream();
                
                wFileName = this.path+File.separator+WB_MAIN_DIR+
                            File.separator+RETAIL_MAIN_DIR+
                            File.separator+RETAIL_FILE_DIR+
                            File.separator+RETAIL_FILE_NAME+
                            /*sdf01.format(fileDate)*/strDates.get(i)+"-"+idFile+RETAIL_ARC_EXT;                
                
                 try{
                        OutputStream out = new FileOutputStream(new File(wFileName));                
                 
                        int read=0;
                        byte[] bytes = new byte[1024];

                        while((read = is.read(bytes))!= -1)
                        {out.write(bytes, 0, read);}

                        is.close();
                        out.flush();
                        out.close();  
                        
                    }catch(IOException e){System.out.println(e);
                                          this.jtextArea.append("\n[-]error al descargar archivo retaillink");
                                         }
                    
                    this.jtextArea.append("\n[-]archivo descargado: "+wFileName);
                    log.info("\n[-]archivo descargado: "+wFileName);
                    
                        CommonDataFile cdf = new CommonDataFile();
                        cdf.writeCommonWebTxtFileRetail(wFileName,cdf.readLiverpoolRetail(wFileName),1,listaFechas.get(i));  
                    
                    this.jtextArea.append("\n[-]archivo procesado: "+wFileName);
            }   
            
            }
           else
           if(indPortalEjec == 0)
           {
             this.jtextArea.append("[-]Portal Retail Link Desactivado");
             log.info("[-]Portal Retail Link Desactivado");           
           }

          }catch(Exception e){System.out.println(e);
                              this.jtextArea.append("\n[-]error al ingresar al portal de retaillink");
                              cef.writeCommonWebTxtFile(errorFilePath,"[-]error al ingresar al portal de retaillink");
                             }
       this.jtextArea.append("\n[-]fin de recuperacion de informacion retaillink: "+wFileName);
    }    
}